package com.supermarket.api.web.admin;

import com.supermarket.api.common.BaseResponse;
import com.supermarket.api.common.logging.NoLog;
import com.supermarket.api.common.utils.DateUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 文件相关接口
 * @author 李其伟
 * @date 2023/11/05
 */
@Api(tags = "文件相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/file")
public class AdminFileController {

    @Value("${apiserver.file.location}")
    private String location;
    @Value("${apiserver.file.url}")
    private String url;

    public final String AVATAR = "upload";
    /**
     *
     * @param file 要上传的文件
     * @return
     */
    @NoLog
    @ResponseBody
    @PostMapping("/avatar")
    public String fileUpload(@RequestParam("file") MultipartFile file){
        // 获取文件名
        String fileName = getFileName(file);

        Date now = new Date();
        String dateStr = DateUtil.parseDateToStr(now, "yyyy/MM/dd");

        String path = location + File.separator + AVATAR + File.separator + dateStr + File.separator;
        //目录不存在，就创建
        File testFile = new File(path);
        if(!testFile.exists()) {
            testFile.mkdirs();
        }

        // 文件对象
        File dest = new File(path +fileName);

        try {
            //保存文件
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //访问URL
        String avatarUrl = url+"/"+AVATAR+"/"+dateStr+"/"+fileName;

        return BaseResponse.successJson(avatarUrl);
    }

    /**
     * 返回文件名
     * @param file
     * @return
     */
    private String getFileName(MultipartFile file){
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
        fileName = UUID.randomUUID()+"."+strArray[suffixIndex];
        return fileName;
    }

}
